package org.demo.client;

import java.io.*;
import java.net.*;

/**
 * Created by tangwy on 2016/1/7.
 */
public class Client {
    private Socket socket = null;
    private PrintStream ps = null;
    private BufferedReader br = null;
    private String clientName;
    public Client(){}
    public Client(String clientName){
        this.clientName=clientName;
    }
    public void start() {
        try {
            //System.out.println(Thread.currentThread().getName());
            socket = new Socket("127.0.0.1", 30000);
            ps = new PrintStream(socket.getOutputStream());
            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            Thread.sleep(2000);
            send(clientName);
            /*new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true){
                        receive();
                    }
                }
            }).start();*/
            /*BufferedReader in = new BufferedReader(new InputStreamReader(
                    socket.getInputStream()));
            PrintWriter out = new PrintWriter(socket.getOutputStream());
            BufferedReader wt = new BufferedReader(new InputStreamReader(System.in));
            while (true) {
                String str = wt.readLine();
                out.println(str);
                out.flush();
                if (str.equals("end")) {
                    break;
                }
                System.out.println(in.readLine());
            }
            socket.close();*/
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void send(String msg) {
        if (!socket.isClosed()) {
            ps.println(msg);
            //receive();
        }
    }

    private void receive() {
        if (!socket.isClosed()) {
            try {
                String msg = br.readLine();
                if("exit".equals(msg)){
                    this.close();
                }else{
                    System.out.println("服务端消息:" + msg);
                    //send("client收到消息");
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void close() {
        try {
            if (!socket.isInputShutdown()) {
                socket.shutdownInput();
            }
            if (!socket.isOutputShutdown()) {
                socket.shutdownOutput();
            }
            if (!socket.isClosed()) {
                socket.close();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
